namespace DotNetNuke.Services.Personalization
{
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;
    using System;
    using System.Runtime.CompilerServices;
    using System.Web;

    public class Personalization
    {
        public static object GetProfile(string NamingContainer, string Key)
        {
            return GetProfile(LoadProfile(), NamingContainer, Key);
        }

        public static object GetProfile(PersonalizationInfo objPersonalization, string NamingContainer, string Key)
        {
            if (objPersonalization != null)
            {
                return objPersonalization.Profile[NamingContainer + ":" + Key];
            }
            return "";
        }

        private static PersonalizationInfo LoadProfile()
        {
            HttpContext context = HttpContext.Current;
            PersonalizationInfo objPersonalization = (PersonalizationInfo) context.Items["Personalization"];
            if (objPersonalization == null)
            {
                PortalSettings _portalSettings = (PortalSettings) context.Items["PortalSettings"];
                UserInfo UserInfo = UserController.GetCurrentUserInfo();
                objPersonalization = new PersonalizationController().LoadProfile(UserInfo.UserID, _portalSettings.PortalId);
                context.Items.Add("Personalization", objPersonalization);
            }
            return objPersonalization;
        }

        public static void RemoveProfile(string NamingContainer, string Key)
        {
            RemoveProfile(LoadProfile(), NamingContainer, Key);
        }

        public static void RemoveProfile(PersonalizationInfo objPersonalization, string NamingContainer, string Key)
        {
            if (objPersonalization != null)
            {
                objPersonalization.Profile.Remove(NamingContainer + ":" + Key);
                objPersonalization.IsModified = true;
            }
        }

        public static void SetProfile(string NamingContainer, string Key, object Value)
        {
            SetProfile(LoadProfile(), NamingContainer, Key, RuntimeHelpers.GetObjectValue(Value));
        }

        public static void SetProfile(PersonalizationInfo objPersonalization, string NamingContainer, string Key, object Value)
        {
            if (objPersonalization != null)
            {
                objPersonalization.Profile[NamingContainer + ":" + Key] = RuntimeHelpers.GetObjectValue(Value);
                objPersonalization.IsModified = true;
            }
        }
    }
}

